package com.example.a1111;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class ExpenseActivity extends AppCompatActivity {

    private EditText amountEditText;
    private EditText dateEditText;
    private DBHelper dbHelper;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_expense);

        amountEditText = findViewById(R.id.amountEditText);
        dateEditText = findViewById(R.id.dateEditText);
        Button saveButton = findViewById(R.id.saveButton);
        Button cancelButton = findViewById(R.id.cancelButton);

        dbHelper = new DBHelper(this);

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveExpense();
            }
        });

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearTextFields();
            }
        });
    }

    private void saveExpense() {
        String amountString = amountEditText.getText().toString();
        String dateString = dateEditText.getText().toString();

        if (!amountString.isEmpty() && !dateString.isEmpty()) {
            double amount = Double.parseDouble(amountString);
            long id = dbHelper.addExpense(amount, dateString);
            if (id != -1) {
                Toast.makeText(ExpenseActivity.this, "Expense saved", Toast.LENGTH_SHORT).show();
                clearTextFields();
            } else {
                Toast.makeText(ExpenseActivity.this, "Failed to save expense", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(ExpenseActivity.this, "Please enter amount and date", Toast.LENGTH_SHORT).show();
        }
    }

    private void clearTextFields() {
        amountEditText.setText("");
        dateEditText.setText("");
    }
}
